<!-- 编辑功能模板 -->
<template>
  <div style="width: 100%; height: 100%; overflow: hidden;">
    <div class="title">
      <div class="name">{{menuName}}</div>
      <div class="butClose" @click="closeWin"></div>
    </div>
    <div class="editBody">
      <div class="groupLine">
        <div class="line"></div>
        <div class="gName">基础信息</div>
        <div class="line"></div>        
      </div>
      <div style="clear: both; width: 100%;">
        <div v-for="item in paramData.params" :style="item.type == 'textarea' ? 'width: 100%; clear: both;' : 'width: 33.3%; float: left;'">
          <field-operate :theData="item" :theOrg="orgId" />
        </div>
      </div>
      <div class="groupLine" style="padding-bottom: 0; padding-top: 10px;">
        <div class="line"></div>
        <div class="gName">明细信息</div>
        <div class="line"></div>        
      </div>
      <!-- 明细列表 -->
      <div class="operateItem">
        <button v-for="item in selectParams"
          style="float: left;"
          class="butSelect"
          @click="openSelect(item)"
        >
          <img src="../assets/img/edit.png"/>{{item.name}}
        </button>
        <button style="float: right;"
            class="butClear"
            @click="clearTableData"
          >
          <img src="../assets/img/detele.png"/>清空
        </button>
      </div>
      <!-- 列表数据 -->
      <div class="tableItem" v-if="tableParam != null && tableParam.length > 0">
      <el-table 
        border
        use-virtual
        highlight-current-row
        :data="dataItems"
        ref="multipleTable"
        class="tableList"
        rowKey="id"
        selectable="true"
        :header-cell-style="{ background:'#FFF' }"
        >
          <el-table-column width="100" label="<< 操 作" fixed>
            <template slot-scope="{ row }">
              <button class="butDelete" @click="deleteDataRow(row)">删 除</button>
            </template>            
          </el-table-column>
          <el-table-column 
            v-for="item in tableParam" 
            :prop="item.null ? ('* '+item.paramName) : item.paramName" 
            :label="item.name" min-width="60"
            :width="item.width"
            v-show="item.hidden"
            :fixed="item.freeze == 1 ? true:false"
            sortable>
            <template slot-scope="scope">
              <div v-if="item.allow">
                <!-- 文本框 -->
                <el-input
                  v-if="item.type == 'text' || item.type == 'textarea'"
                  type="text"
                  v-model="scope.row[item.paramName]"
                  :maxlength="item.maxLength"
                  @change="((val)=>updateItemValue(val,scope.row,item.paramName))"
                ></el-input>
                <!-- 数字 -->
                <el-input
                  v-else-if="item.type == 'int' || item.type == 'float'"
                  type="number"
                  v-model="scope.row[item.paramName]"
                  :maxlength="item.maxLength"
                  @change="((val)=>updateItemValue(val,scope.row,item.paramName))"
                ></el-input>
                <!-- 单选 -->
                <el-switch
                  v-else-if="item.type == 'radio'"
                  :v-model="scope.row[item.actionValue] === '1'"
                  :active-value="true"
                  :inactive-value="false"
                  active-color="#00A578"
                  inactive-color="#BFBFBF"
                  @change="((val)=>updateItemValue(val,scope.row,item.actionValue))"
                ></el-switch>
                <!-- 日期 -->
                <el-date-picker
                  v-else-if="item.type.trim().toLowerCase().includes('datetime')"
                  v-model="scope.row[item.paramName]"
                  type="date"
                  value-format="yyyy-MM-dd"
                  @change="((val)=>updateItemValue(val,scope.row,item.paramName))"
                ></el-date-picker>
                <!-- 下拉选 -->
                <el-select
                  v-else-if="item.type.trim().toLowerCase().includes('select')"
                  v-model="scope.row[item.paramName]"
                  @change="((val)=>updateItemValue(val,scope.row,item.actionValue))"
                >
                  <el-option
                    v-for="opItem in item.selectItems"
                    :label="opItem.title"
                    :value="opItem.value"
                    :key="opItem.title"
                  ></el-option>
                </el-select>
              </div>
              <div v-else>
                <span v-if="scope.row[item.paramName]">{{scope.row[item.paramName]}}</span>
                <span v-else style="font-size: 18px;">-</span>
              </div>
            </template>
          </el-table-column>
          <template slot="empty">
            <div class="notData">
              <img src="../assets/img/notData.png" />暂无数据
            </div>
          </template>
        </el-table>      
      </div>
    </div>
    <div class="button">
      <button class="butTwo" @click="closeWin">取 消</button>
      <button class="butOne" @click="submitData">保 存</button>
    </div>
    <div class="floatBG2" v-show="allowOpen"></div>
    <div class="selectData" v-show="allowOpen == true && openType == 'selectData'">
      <select-data :theData="openData" :theOrg="orgId"></select-data>
    </div>
    <div class="typeData" v-show="allowOpen == true && openType == 'typeData'">
      <type-data :theData="openData" :theOrg="orgId"></type-data>
    </div>
  </div>
</template>
<script>
import selectData from "./selectData.vue";
import typeData from "./typeData.vue";
import fieldOperate from "./fieldOperate.vue";
export default {
  data() {
    return {
      menuName: "",
      menuKey: "",
      dataId:0,
      orgId:0,
      limitState:0,
      limitClew:'',
      openData:{},
      paramData:{},
      tableData:{},
      detailData:{},
      tableParam:[],
      dataItems:[],
      selectParams:[],
      openType:'',
      showUrl:'',
      submitUrl:'',
      allowOpen: false
    };
  },
  components:{
    selectData,
    typeData,
    fieldOperate
  },
  props:{
    menuData:{
      type:Object,
      required:true
    },
    theOrg:{
      type:Number,
      required:true
    }
  },
  created() {
    
  },
  watch: {
    menuData(data){
      this.menuKey = this.menuData.key;
      this.menuName = this.menuData.name;
      this.dataId = this.menuData.dataId;
      this.orgId = this.theOrg;
      this.paramData = {};
      this.tableData = {};
      this.detailData = {};
      this.tableParam = [];
      this.dataItems = [];
      this.selectParams = [];
      this.submitUrl = '';
      this.showUrl = '';
      if(this.menuData.openType == 'orderEdit')
        this.showData();
    }
  },
  methods: {
    //显示数据与组件
    async showData(){
      if(this.menuData != null && this.menuData.showUrl != null){        
        let toUrl = this.changeUrl(this.menuData.showUrl);
        let { data: res } = await this.$http.get(toUrl);
        if (res.result) {
          this.limitState = res.obj.showState;
          this.limitClew = '';
          if(this.limitState != null && this.limitState > 0){
            if(this.limitState == 1)
              this.limitClew = '已审核';
            else if(this.limitState == 2)
              this.limitClew = '已禁用';
          }
          //单头数据
          this.submitUrl = res.obj.submitUrl;
          this.paramData = res.obj.formParam;
          this.menuName = res.obj.menuName;
          for(let item of this.paramData.params.filter(x => x.allow)){
            if(item.type.toLowerCase().includes('select') || item.type == 'radio'){
              let theVal = item.selectValue ? item.selectValue.toString() : '0';
              this.tableData[item.actionValue] = theVal.toString();
            } else{
              this.tableData[item.paramName] = item.value;
            }            
          }
          //单体数据
          this.detailData = res.obj.tableParam;
          this.tableParam = this.detailData.params;
          if(this.detailData.items != null  && this.detailData.items.length > 0){            
            this.dataItems = this.detailData.items;
            this.updateDataItemIndex();
          }
          else
            this.dataItems = [];
          this.selectParams = this.detailData.selectParams;
        }else{
          this.clewMsg(res.type,res.msg);
        }
      }
    },
    //提交保存数据
    async submitData(){
      if(this.limitState <= 0){
        var verifyItems = this.paramData.params.filter(x => x.allow && x.null);
        var verify = true;
        var message = '请注意：<br/><br/>';
        //效验单头字段，是否存在必填字段为空
        for(let item of verifyItems){          
          if(item.type != 'radio'){
            let theVal = item.type.toLowerCase().includes("select") ? 
              this.tableData[item.actionValue] : this.tableData[item.paramName];
            if(item.type == 'int' || item.type == 'float' || item.type.toLowerCase().includes("select")){            
              if(theVal == null || theVal <= 0){
                message += '字段#'+item.name+'#，为必填项，请确认;<br/>';
                verify = false;
              }
            }else{
              if(theVal == null || theVal.trim().length <= 0) {
                message += '字段#'+item.name+'#，为必填项，请确认;<br/>';
                verify = false;
              }
            }
          }          
        }
        if(verify){
          //执行提交数据
          if(this.dataItems != null && this.dataItems.length > 0){
            this.tableData['id'] = this.dataId.toString();
            var postUrl = this.submitUrl;
            let theDataItems = this.dataItems.map(obj => {
              delete obj['index'];
              return obj;
            });
            var dataParam = '{ '+this.menuKey+'Data: '+JSON.stringify(this.tableData)+','+this.menuKey+'Details: '+JSON.stringify(theDataItems)+' }';
            var postData = {
              dataId: this.dataId,
              orgId: this.theOrg,
              menuKey: this.menuKey,
              dataParam: dataParam
            };
            let { data: res } = await this.$http.post(postUrl, postData);
            if (res.result) {
              this.clewMsg(1,'操作成功');
              this.dataId = res.dataId;
              if(this.dataId > 0 && this.menuName.includes('新增')){
                this.menuName.replace('新增','编辑');
              }
            } else {
              this.clewMsg(res.type,res.msg);
            }
          }else{
            this.clewMsg(3,'请选填明细行数据');
          }          
        }else{
          this.clewMsg(3,message);
        }
      }else{
        this.clewMsg(2,'很抱歉，该单据处于#'+this.limitClew+'#，不能操作');
      }
    },
    //更新明细数据
    async updateListData(selectIds,returnUrl,returnType){      
      var menuKey = this.getUrlParam(returnUrl,'menuKey');
      var toUrl = returnUrl.split('?')[0];
      var postData = {
        menuKey: menuKey,
        orgId: this.theOrg,
        selectedIds: selectIds,
        returnType: returnType
      };
      let { data: res } = await this.$http.post(toUrl,postData);
      if (res.result) {
        let selectItems = res.obj;
        let index = this.dataItems != null && this.dataItems.length > 0 ? this.dataItems.length : 0;
        for(let x in selectItems){
          var obj = selectItems[x];
          var theData = {};
          for(let i in this.tableParam) {
            var item = this.tableParam[i];
            if(item.type === 'autoReturn'){
              if(item.actionValue != null && item.actionValue.length > 0){
                theData[item.actionValue] = obj[item.lockKey];
              }
              theData[item.paramName] = obj[item.returnKey];
            }else{
              if(item.type.toLowerCase().includes("select") || item.type === 'radio'){
                theData[item.actionValue] = '';
                theData[item.paramName] = '';
              }else{
                theData[item.paramName] = '';
              }
            }
            theData['index'] = index;
          }
          index++;
          this.dataItems.push(theData);
          this.closeSubWin();
        }        
      }else{
        this.clewMsg(res.type,res.msg);
      }
    },
    //重新排列顺序
    updateDataItemIndex(){
      if(this.dataItems != null  && this.dataItems.length > 0){            
          let num = 0;
          let theDataItems = this.dataItems;
          theDataItems.forEach(obj => {
            if(obj.hasOwnProperty('index')){
              obj['index'] = num;
            }else{
              Object.assign(obj,{index: num});              
            }            
            num++;
          });
          this.dataItems = theDataItems;
        }
    },
    //字段单头修改值
    updateChangeVal(data){
      console.log('update data:>>');
      console.log(data);
      this.tableData[data.param] = data.value.toString();
    },
    //修改行字段值
    updateItemValue(val,row,param){
      console.log('detail line data['+row.index+']:>> ' + val);
      console.log(row);
      this.dataItems.forEach(obj => {
        if(obj.index === row.index){
          obj[param] = val.toString();
        }
      });
    },    
    //清空所有行数据
    clearTableData(){
      this.dataItems = [];
    },
    //删除指定行数据
    deleteDataRow(row) {
      if(row != null && row.index != null && row.index >= 0){
        this.dataItems.splice(row.index, 1);
        this.updateDataItemIndex();
      }
    },
    //分解URL参数取值
    getUrlParam (url,paraName) {
      var arrObj = url.split("?");
      if (arrObj.length > 1) {
          var arrPara = arrObj[1].split("&");
          var arr;
          for (var i = 0; i < arrPara.length; i++) {
              arr = arrPara[i].split("=");
              if (arr != null && arr[0] == paraName) {
                return arr[1];
              }
            }
            return "";
          } else {
            return "";
      }
    },
    //打开选项类别窗口
    openTypeWin(data) {
      this.openData = data;
      this.openType = 'typeData';
      this.allowOpen = true;
    },
    //打开基础档案选择窗口
    openWin(data) {
      this.openData = data;
      this.openData.searchType = 'common';
      this.openData.selectType = 'select';
      this.openData.returnType = 'main';
      this.openType = 'selectData';
      this.allowOpen = true;
    },
    //打开单据明细选择窗口
    openSelect(data) {
      this.openData = {
        name: data.name,
        key: data.menuKey,
        url: data.actionUrl,
        filter: data.filter,
        search: data.search,
        lockKey: data.lockKey,
        selectType: 'selectMany',
        searchType: 'detailSelect',
        returnType: 'detail'
      };
      this.openType = 'selectData';
      this.allowOpen = true;
    },
    //关闭子窗口
    closeSubWin(){
      this.allowOpen = false;
      this.openType = '';
      this.openData = {};
    },
    //关闭本窗体
    closeWin(){
      this.$parent.closeEdit();
    },    
    //处理URL自增加组织ID
    changeUrl(url){
      if(/\?|&/.test(url)){
        url += '&orgId=' + this.theOrg;
      }else{
        url += '?orgId=' + this.theOrg;
      }      
      console.log("changeURL:" + url);
      return url;
    },
    //提款信息
    clewMsg(type,mes){
      var theType = 'warning';
      if(type == 1)
        theType = 'success';
      else if(type == 3)
        theType = 'error';
      this.$message({
        dangerouslyUseHTMLString:true,
        message: mes,
        type: theType
      });
    }
  }
};
</script>
<style lang="less" scoped>
  .tableItem{
    clear: both;
    width: 100%;
    align-items: center;
    padding: 0;
    margin: 0;
    /deep/.el-table{
      width:100%;
      overflow: auto;
      max-height:calc(100% - 200px);
    }
    /deep/.el-table__header th{
      background: #EEE;
      font-weight:normal;
      color: #000;
    }
    /deep/.el-table__header .el-table__cell{
      padding: 5px 0;
    }
    /deep/.el-table__body-wrapper{
      width:100%;
    }
    /deep/tr .el-checkbox__input{
      margin-left: 10px;
    }
    /deep/td .el-checkbox__input{
      margin-left: 10px;
    }
    /deep/.el-checkbox__inner{
      width: 18px;
      height: 18px;
    }
    /deep/.el-checkbox__inner:hover{
      border-color: #00A578;
      box-shadow: 0 0 2px 1px rgba(42, 51, 49, 0.15);
    }
    /deep/.el-table thead{
      color: #FFF;
    }
    /deep/.el-table__empty-block{
      width: 0px;
    }
    /deep/.el-table__empty-text{
      text-align: left;
    }    
  }
</style> 
<style>
  .operateItem{
    width: calc(100% - 20px);
    padding: 0 10px;
    height: 40px;
    margin-bottom: 10px;
    clear: both;
  }
  .butSelect{
    padding: 6px 12px;
    height: 34px;
    line-height: 24px;
    font-size: 15px;
    color: #00A578;
    border-radius: 6px;
    margin-right: 10px;
    border: none;
    background: none;
    cursor: pointer;
    text-align: center;
  }
  .butClear{
    padding: 6px 12px;
    height: 34px;
    line-height: 24px;
    margin-left: 10px;
    font-size: 15px;
    color: #E8241F;
    border-radius: 6px;
    border: none;
    background: none;
    cursor: pointer;
    text-align: center;
  }
  .butDelete{
    padding: 5px;
    height: 34px;
    line-height: 24px;
    font-size: 15px;
    color: #E8241F;
    border-radius: 6px;
    border: none;
    background: none;
    cursor: pointer;
  }
  .operateItem > button:hover{
    background-color: #EEE;
  }
  .operateItem > button img{
    height: 14px;
    margin-right: 8px;
    width:auto;
  }
  .title{
    clear: both;
    width: calc(100% - 50px);
    height: 40px;
    padding: 8px 25px;
    border-bottom: solid 1px #DDD;
  }  
  .name{
    float: left;
    height: 40px;
    line-height: 40px;
    color: #555;
    font-size: 16px;
    text-align: left;
  }
  .butClose{
    float: right;
    height: 40px;
    width: 40px;
    cursor: pointer;
    background: url(../assets/img/close.png) no-repeat;
    background-size: 50% 50%;
    background-position: center right;
  }  
  .editBody{
    clear: both;
    padding: 20px 20px 40px 20px;
    width: calc(100% - 40px);
    max-height: 420px;
    overflow-x: hidden;
    overflow-y: auto;
  }
  .button{
    clear: both;
    width: calc(100% - 20px);
    height: 40px;
    padding: 10px;
    border-top: solid 1px #DDD;
    align-items: right;
    text-align: right;
  }
  .groupLine{
    display: flex;
    width: 100%;
    margin: 0 auto;
    padding-bottom: 10px;
    .line{
        flex: 1;
        position: relative;
        top: -12px;
        border-bottom: 1px solid #EEE;
    }
    .gName{
        padding: 0 14px;
        font-size: 16px;
        color:#666;
    }
  }
  .selectData{
    position: fixed;
    z-index: 777;
    top: 100px;
    left: calc((100% - 1300px) / 2);
    width: 1300px;
    max-height: 580px;
    overflow: hidden;
    background: #FFF;
    border-radius: 5px;
    box-shadow: 0 1px 2px 1px rgba(0,0,0,0.15);
  }
  .typeData{
    position: fixed;
    z-index: 888;
    top: 100px;
    left: calc((100% - 800px) / 2);
    width: 800px;
    max-height: 650px;
    overflow: hidden;
    background: #FFF;
    border-radius: 5px;
    box-shadow: 0 1px 2px 1px rgba(0,0,0,0.15);
  }
  .floatBG2{
    position: fixed;
    z-index: 556;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.3);
  }
</style>
